<!-- ---------------------------------------游玩分类页面 ------------------------------------------------>
<template>
    <div>
        <!-- 分类列表展示区域 -->
        <div v-show="activeStatu">
            <el-card class="box">
                <div class="card-content">
                    <!-- 搜索和筛选条件区域 -->
                    <div class="flex search-header">
                        <div class="filter-label">分类标题</div>
                        <div class="time_top">创建时间</div>
                    </div>
                    <div class="flexBox search-filters">
                        <div>
                            <!-- 分类名称搜索输入框 -->
                            <el-input v-model.trim="inputed" @input="filters" placeholder="输入内容" class="search-input">
                                <template #prefix>
                                    <el-icon class="el-input__icon">
                                        <search />
                                    </el-icon>
                                </template>
                            </el-input>
                        </div>
                        <!-- 日期范围选择器 -->
                        <div class="date-picker-container">
                            <el-date-picker class="date-picker" @change="data_filters" v-model="time" type="daterange"
                                range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
                        </div>
                    </div>
                    <!-- 操作按钮区域 -->
                    <div class="action-buttons">
                        <div><el-button type="primary" @click="add" class="add_class">
                                新增</el-button>
                        </div>
                        <el-button type="danger" class="delelist" @click="deleList">批量删除</el-button>
                    </div>

                    <!---------------------------- table表格数据展示 ---------------------------->
                    <div class="table-container">
                        <el-table :data="activeList.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
                            class="data-table" :cell-style="{ 'text-align': 'center' }" lazy="true" height="auto"
                            v-el-table-infinite-scroll="handleTableScroll"
                            :header-cell-style="{ 'text-align': 'center' }" @selection-change="handleSelectionChange">
                            <el-table-column type="selection" fixed="left" />
                            <el-table-column prop="id" label="序号" fixed="left" />
                            <el-table-column prop="title" label="分类名称" show-overflow-tooltip />
                            <el-table-column prop="createtime" label="创建时间" />
                            <el-table-column label="操作" width="250" fixed="right">
                                <template #default="scope">
                                    <div class="handle">
                                        <div @click="edit(scope.row)" class="action-edit">编辑</div>
                                        <div class="action-separator"></div>
                                        <div @click="deletes(scope.row)" class="action-delete">删除</div>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>

                    <!-- 分页控件 -->
                    <div class="paging">
                        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                            :page-sizes="[5, 10, 20, 50]" :small="small" :disabled="disabled" background
                            layout="total, sizes, prev, pager, next, jumper" :total="activeList.length" />
                    </div>

                    <!-- 单个删除确认对话框 -->
                    <el-dialog title="删除" v-model="centerDialogVisible" width="30%" center>
                        <div class="dialog-message">确认删除该游玩吗?</div>
                        <div class="dialog-buttons">
                            <el-button @click="centerDialogVisible = false">取 消</el-button>
                            <el-button type="primary" @click="deleteid">确 定</el-button>
                        </div>
                    </el-dialog>
                </div>

                <!-- 旧的确认对话框，代码中未使用 -->
                <el-dialog v-model="shows" title="是否要删除" center width="20vw">
                    <el-button @click="shows = false">取 消</el-button>
                    <el-button type="primary" @click="oks">确 定</el-button>
                </el-dialog>

                <!-- 批量删除确认对话框 -->
                <el-dialog title="批量删除" v-model="centerDialogVisiblet" width="30%" center>
                    <div class="dialog-message">确认删除这批数据吗?</div>
                    <span slot="footer" class="dialog-footer">
                        <div></div>
                        <div class="dialog-buttons">
                            <el-button @click="centerDialogVisiblet = false">取 消</el-button>
                            <el-button type="primary" @click="deleteid_t">确 定</el-button>
                        </div>
                    </span>
                </el-dialog>
            </el-card>
        </div>

        <!-- --------------------------新增/编辑分类表单区域---------------------------->
        <div v-show="activeStatud" class="form-container">
            <el-card class="form-card">
                <div class="form-header">{{ addText }}</div>
                <div class="divider"></div>

                <!-- 表单区域 -->
                <div class="form-content">
                    <el-form ref="ruleFormRef" class="rule-form" :model="ruleForm" status-icon :rules="rules"
                        label-position="left" label-width="auto">
                        <el-form-item label="分类名称" prop="name" class="form-item">
                            <el-input v-model.trim="ruleForm.name" placeholder="请输入" class="full-width-input"
                                @blur="checkDuplicate" />
                        </el-form-item>
                    </el-form>

                    <!-- 表单操作按钮 -->
                    <div class="form-actions">
                        <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
                        <el-button @click="closes(ruleFormRef)">取消</el-button>
                    </div>
                </div>
            </el-card>
        </div>
    </div>
</template>
<script setup>
import { ref, reactive } from 'vue';
import { active, activeAdd, activeDel } from '../../../api/active/index';
import { ElMessage, ElCard } from 'element-plus';

// 数据筛选相关变量
const time = ref('')
// 分类列表数据
const activeList = ref([]);
// 控制分类列表显示状态
const activeStatu = ref(true)
// 控制新增/编辑表单显示状态
const activeStatud = ref(false)
// 注入测试函数
import { inject } from 'vue'
const testFn = inject('testFn')
testFn()

const dialogTableVisible = ref(false);
// 状态标记：1-新增，2-编辑
const statused = ref('1');
// 表格分页相关变量
const inputed = ref('');
const pageSize = ref(5);
const currentPage = ref(1);
// 保存原始数据用于筛选
const copyList = ref([]);
const files = ref(false);

// 分类名称查重相关变量
const categoryExists = ref(false);
const categoryName = ref('');
// 保存编辑前的原始名称
const originalName = ref('');

// 获取本地存储的用户认证信息
let tokens = JSON.parse(localStorage.getItem('tokens'));
// 页面加载时初始化数据
render();

// 渲染分类列表数据
function render() {
    active({
        token: tokens.token,
        uid: tokens.userinfo.id
    }, {
        userid: tokens.userinfo.id
    }).then((res) => {
        console.log(res);
        activeList.value = res.data;
        copyList.value = res.data;
    });
}

// 控制表单标题文本
const addText = ref("")
// 点击新增按钮处理函数
function add() {
    activeStatu.value = false
    addText.value = '添加'
    activeStatud.value = true
    dialogTableVisible.value = true;
    statused.value = '1';
    disableds.value = true;
    // 重置表单数据
    (ruleForm.name = ''), (ruleForm.start_time = ''), (ruleForm.end_time = ''), (ruleForm.details = ''), (ruleForm.img = ''), (ruleForm.synopsis = '');
    categoryExists.value = false;
    categoryName.value = '';
    originalName.value = ''; // 新增时没有原始名称
}

// --------------------------表单对象--------------------------
const ruleForm = reactive({
    name: '',
    start_time: '',
    end_time: '',
    details: '',
    img: '',
    synopsis: '',
});
const ruleFormRef = ref('');

// 表单验证规则
const rules = reactive({
    name: [
        {
            required: true,
            message: '请输入分类名称',
            trigger: 'blur',
        },
        {
            validator: (rule, value, callback) => {
                if (categoryExists.value && value === categoryName.value) {
                    callback(new Error('分类名称已存在'));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ],
    start_time: [
        {
            required: true,
            message: '请选择开始时间',
            trigger: 'blur',
        },
    ],
    end_time: [
        {
            required: true,
            message: '请输入结束时间',
            trigger: 'blur',
        },
        { validator: validateEmailDomain, trigger: 'blur' }
    ],
    details: [
        {
            required: true,
            message: '请输入活动详情',
            trigger: 'blur',
        },
    ],
    img: [
        {
            required: true,
            message: '请上传图片',
            trigger: 'change',
        },
    ],
    synopsis: [
        {
            required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
                if (!value) {
                    callback(new Error('请输入活动简介'));
                } else if (value.length > 19) {
                    callback(new Error('仅最多输入20个字'));
                } else {
                    callback();
                }
            },
        },
    ],
});

//-------------------------- 判断开始结束时间--------------------------
function validateEmailDomain(rule, value, callback) {
    if (value === '') {
        callback(new Error('结束时间不能为空'));
    } else if (value < ruleForm.start_time) {
        // 假设我们只允许 @example.com 的邮箱  
        callback(new Error('结束时间不能小于开始时间'));
    } else {
        callback();
    }
}

// --------------------------使用本地数据进行查重--------------------------
function checkDuplicate() {
    // 如果输入为空则不进行查重
    if (!ruleForm.name.trim()) return;

    // 编辑状态下，如果名称与原始名称相同，则不进行查重
    if (statused.value === '2' && ruleForm.name === originalName.value) {
        categoryExists.value = false;
        categoryName.value = '';
        return;
    }

    // 在本地数据中查找是否存在相同的分类名称
    const exists = activeList.value.some(item =>
        item.title === ruleForm.name.trim() &&
        // 编辑状态下，排除当前编辑的项
        (statused.value !== '2' || item.id !== ids.value)
    );

    if (exists) {
        categoryExists.value = true;
        categoryName.value = ruleForm.name.trim();
        ElMessage.warning('该分类名称已存在');
    } else {
        categoryExists.value = false;
        categoryName.value = '';
    }
}

const imgUrls = ref('');

// --------------------------点击确认新增或编辑--------------------------
const submitForm = (formEl) => {
    console.log(ruleForm);
    if (!formEl) return;

    // 表单验证
    formEl.validate((valid) => {
        if (valid) {
            // 再次检查名称是否存在
            if (categoryExists.value && ruleForm.name === categoryName.value) {
                ElMessage.warning('分类名称已存在');
                return;
            }

            // 新增操作
            if (statused.value == '1') {
                ruleForm.img = imgUrls.value;
                console.log(ruleForm);
                activeAdd({ token: tokens.token, uid: tokens.userinfo.id }, { userid: tokens.userinfo.id, title: ruleForm.name }).then((res) => {
                    if (res.code == '1') {
                        ElMessage({
                            message: '新增成功',
                            type: 'success',
                        });
                        setTimeout(() => {
                            activeStatud.value = false;
                            activeStatu.value = true;
                        }, 1200);
                        render();
                    }
                });
            }
            // 编辑操作
            else if (statused.value == '2') {
                ruleForm.img = imgUrls.value;
                activeAdd({ token: tokens.token, uid: tokens.userinfo.id }, { userid: tokens.userinfo.id, id: ids.value, title: ruleForm.name }).then((res) => {
                    if (res.code == '1') {
                        ElMessage({
                            message: '编辑成功',
                            type: 'success',
                        });
                        setTimeout(() => {
                            activeStatud.value = false;
                            activeStatu.value = true;
                        }, 1200);
                        render();
                    } else {
                        ElMessage({
                            message: '编辑失败，不能和原数据一致',
                            type: 'warning',
                        });
                    }
                });
            }
        }
        else {
            ElMessage({
                message: '新增失败',
                type: 'error',
            });
        }
    });
};

const ids = ref('');
const disableds = ref(true);

// --------------------------关闭新增/编辑表单--------------------------
const closes = (formEl) => {
    console.log(formEl);
    activeStatu.value = true
    activeStatud.value = false
    formEl.resetFields();
    formEl.clearValidate()
    dialogTableVisible.value = false;
    files.value = false;
    ruleForm.name = '';
    categoryExists.value = false;
    categoryName.value = '';
    originalName.value = '';
};

// --------------------------点击编辑--------------------------
function edit(item) {
    // Object.assign(ruleForm, item);
    addText.value = '编辑'
    ids.value = item.id;
    activeStatud.value = true
    activeStatu.value = false
    ruleForm.name = item.title
    disableds.value = false;
    statused.value = '2';
    originalName.value = item.title; // 保存编辑前的原始名称
}

// --------------------------点击删除出现弹窗--------------------------
function deletes(item) {
    console.log(item);
    centerDialogVisible.value = true;
    deleteids.value = item.id;
}

const deleteids = ref('');
const centerDialogVisible = ref(false);

//-------------------------- 确认删除--------------------------
function deleteid() {
    activeDel(
        {
            token: tokens.token,
            uid: tokens.userinfo.id,
        },
        {
            userid: tokens.userinfo.id,
            id: deleteids.value,
        }
    ).then((res) => {
        if (res.code == '1') {
            centerDialogVisible.value = false;
            ElMessage({
                message: '删除成功',
                type: 'success',
            });
            render();
        }
    });
}

// --------------------------分类名称搜索--------------------------
function filters() {
    currentPage.value = 1
    console.log(inputed.value);
    let a = [];
    // 筛选匹配分类名称的数据
    activeList.value = copyList.value.filter(function (item) {
        // 判断是否满足搜索条件
        if (String(item.title).indexOf(String(inputed.value)) > -1) {
            return a;
        }
    });
    currentPage.value = 1
}

//-------------------------- 分类日期搜索//--------------------------
const data_filters = () => {
    let end_time
    let start_time
    let ars = []
    if (time.value) {
        end_time = Date.parse(new Date(time.value[0]))
        start_time = Date.parse(new Date(time.value[1]))
    }
    // 按日期范围筛选数据
    activeList.value = copyList.value.filter((item) => {
        if (item.title ?
            item.title.indexOf(inputed.value) > -1 &&
            (time.value ?
                Date.parse(new Date(`${item.createtime}`)) > end_time &&
                Date.parse(new Date(` ${item.createtime}`)) < start_time : true
            ) : true
        ) {
            return item
        }
        ars.push(item)
    });
}

const shows = ref(false);

// 删除批量
// 全选单选
const SelectArr = ref([])
const All_Delete = ref([])

// 表格选择变化处理函数
const handleSelectionChange = (val) => {
    All_Delete.value = []
    SelectArr.value = val
    SelectArr.value.forEach(item => {
        console.log(item);
        All_Delete.value.push(item.id)
    })
    console.log(All_Delete.value);
}

// 批量删除
const centerDialogVisiblet = ref(false)
const st = ref([])

// 批量删除按钮处理函数
function deleList() {
    st.value = []
    console.log(All_Delete.value);
    st.value.push(All_Delete.value)
    if (All_Delete.value == '') {
        ElMessage({
            message: '请勾选要删除的游玩',
            type: 'warning',
        })
    } else {
        centerDialogVisiblet.value = true
    }
}

// 确认批量删除
const deleteid_t = () => {
    activeDel({
        token: tokens.token,
        uid: tokens.userinfo.id
    }, {
        userid: tokens.userinfo.id,
        id: st.value.join(','),
    }).then(res => {
        console.log(res, '删除成功或失败回调');
        centerDialogVisiblet.value = false;
        render();
        ElMessage({
            message: '删除成功',
            type: 'success',
        })
    })
}
</script>

<style scoped>
/* 基础样式 */
.text {
    font-size: 14px;
}

.item {
    margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
    display: table;
    content: '';
}

.clearfix:after {
    clear: both;
}

.box-card {
    display: flex;
    height: 300px;
    width: 90%;
}

.handle {
    display: flex;
    align-items: center;
    justify-content: center;
}

/* 布局样式 */
.paging {
    display: flex;
    justify-content: center;
    margin-top: 10px;
    height: 70px;
}

.flex {
    display: flex;
    align-items: center;
    padding-bottom: 10px;
}

.flexBox {
    display: flex;
    width: 100%;
    align-items: center;
}

/* 卡片内容区域 */
.card-content {
    padding: 10px;
}

/* 搜索区域 */
.search-header {
    padding-bottom: 10px;
}

.filter-label {
    width: 220px;
}

.search-filters {
    margin-bottom: 20px;
}

.search-input {
    width: 220px;
}

.date-picker-container {
    margin-left: 20px;
}

.date-picker {
    width: 220px;
}

/* 操作按钮 */
.action-buttons {
    display: flex;
    margin-bottom: 20px;
}

.add_class {
    margin-right: 10px;
}

/* 表格 */
.table-container {
    margin-top: 10px;
}

.data-table {
    width: 100%;
}

/* 操作列样式 */
.action-edit {
    color: rgba(64, 158, 255, 1);
    cursor: pointer;
}

.action-separator {
    width: 10px;
}

.action-delete {
    color: red;
    cursor: pointer;
}

/* 对话框 */
.dialog-message {
    font-size: 16px;
    padding-bottom: 20px;
}

.dialog-buttons {
    display: flex;
    justify-content: flex-end;
}

.dialog-footer {
    display: flex;
    justify-content: space-between;
}

/* 表单区域 */
.form-container {
    padding: 10px;
}

.form-card {
    width: 96%;
    margin-left: 2%;
    margin-top: 1%;
    position: relative;
    height: 80vh;
}

.form-header {
    padding: 10px;
}

.divider {
    width: 100%;
    height: 1px;
    background-color: rgba(195, 195, 195, 1);
}

.form-content {
    margin-top: 20px;
}

.rule-form {
    width: 40%;
    margin-top: 50px;
    margin-left: 100px;
}

.form-item {
    width: 100%;
}

.full-width-input {
    width: 100%;
}

.form-actions {
    position: absolute;
    bottom: 20px;
    right: 40px;
}

/* 日期选择器样式调整 */
.el-date-range-picker__content {
    box-sizing: border-box;
    float: left;
    margin: 0;
    padding: 16px;
    width: 38%;
}
</style>